<template>
	<view class="example-task">
		<view class="example-info" v-if="exampleInfo.id">
			<view class="head">
				<image :src="exampleInfo.pictureUrl" mode="aspectFill"></image>
			</view>
			<view class="name-time">
				<view class="name-see">
					<text class="name">我的重要他人：{{exampleInfo.name}}</text>
					<view class="see-details" v-if="!accountId" @click="seeDetails()">
						<text>查看详情</text>
						<uni-icons type="right" color="#999999" size="28rpx"></uni-icons>
					</view>
				</view>
				<view class="time" v-if="taskStartTime">
					任务期限：{{taskStartTime}}日 - {{taskDeadline}}日
				</view>
			</view>
		</view>
		<view class="example-info" v-else>
			<view>还未设置重要他人</view>
		</view>
		<view>
			<view class="pro-exp-box" v-if="!accountId">
				<view class="pro-exp-title" @click="selectTask()">
					<view class="" v-if="!selectTaskInfo.id">
						<uni-icons type="plusempty" size="28rpx" color="#333333"></uni-icons>
						<text>添加任务对齐</text>
					</view>
					<view class="" v-else>
						{{selectTaskInfo.content}}
					</view>
				</view>
				<view class="textarea-box">
					<view class="task-completion">
	
						<text-editor id-name="editorTask" ref="editorTask" 
							:info="editorInfo"
							:userId="userId"
							@chooseFile="chooseFileTask" @closePopup="closePopup"></text-editor>

						<view class="all-img-file">
							<view class="imgs">
								<view class="img-box" v-for="(item, i) in sendImages" :key="i">
									<image class="img" :src="api.xiaodeObsUrl+item.path" mode="aspectFill"></image>
									<image class="close" @click="delFiles(i, sendImages)" src="/static/chat/close.png" mode="aspectFill"></image>
								</view>
							</view>
							<view class="files">
								<view class="file-box" v-for="(item, i) in sendfiles" :key="i">
									<zy-file :src="item.path" :name="item.name" :size="item.size"></zy-file>
									<image class="close" @click="delFiles(i, sendfiles)" src="/static/chat/close.png" mode="aspectFill"></image>
								</view>
								
							</view>
						</view>
					</view>
					<view class="key-result" v-if="keyResults.length>0">
						<view class="kr-list" v-for="(item, index) in keyResults" :key="index">
							<view class="k-text">
								<textarea
								placeholder="添加关键结果，将纳入到你的活动足迹中"
								 @input="(e)=>bindinput1(e, index)" @focus="e=>bindfocus1(e, index)" @blur="(e)=>bindblur1(e, index)" :value="keyResults[index]?keyResults[index].content:''" auto-height maxlength="500" :hold-keyboard="true" :auto-blur="true" cursor-spacing="30"/>
								<uni-icons @click="delResults(index)" type="minus" color="#999999"></uni-icons>
							</view>
							<view class="all-img-file" v-if="keyResults[index]">
								<view class="imgs">
									<view class="img-box" v-for="(info, i) in keyResults[index].sendimgs" :key="i">
										<image class="img" :src="api.xiaodeObsUrl+info.path" mode="aspectFill"></image>
										<image class="close" @click="delkeyFiles(i, '1', index, keyResults[index])" src="/static/chat/close.png" mode="aspectFill"></image>
									</view>
								</view>
								<view class="files">
									<view class="file-box" v-for="(info, i) in keyResults[index].sendfiles" :key="i">
										<zy-file :src="info.path" :name="info.name" :size="info.size"></zy-file>
										<image class="close" @click="delkeyFiles(i, '8', index, keyResults[index])" src="/static/chat/close.png" mode="aspectFill"></image>
									</view>
								</view>
							</view>
						</view>
					</view>
					<view class="add-btn" @click="addResults()">
						<uni-icons type="plusempty" size="28rpx" color="#333333"></uni-icons>
						<text>添加关键结果</text>
					</view>
				</view>
				<view class="time-publish">
					<view class="pub-btn" @click="commitExampleActivity" :style="{opacity: utils.editorCont(editorInfo.content)&&selectTaskInfo.id?'1':'.3'}">立即发布</view>
				</view>
			</view>
			<view class="pro-exp-box" v-for="(item, inx) in vocationLabourList" :key="inx">
				<view class="pro-exp-title">
					<view class="">
						{{item.task_alignment}}
					</view>
					<text class="state" :class="[{state1: item.state==1, state2: item.state==2}]">{{item.state==1?'待审核':item.state==2?'已完成':'待完成'}}</text>
				</view>
				<view class="textarea-box1">
					<view class="task-completion" :class="{'task-line': item.keyResultsTaskList}">
						<text-editor v-if="item.content" :id-name="`editorList${item.id}`" :ref="`editorList${item.id}`" :read-only="true" 
							:info="{content: item.content, height: 'auto'}"></text-editor>
						<view class="all-img-file" v-if="item.dst_imgs || item.files_show">
							<view class="imgs">
								<view class="img-box" v-for="(path, i) in item.dst_imgs" :key="i">
									<image class="img" :src="path" mode="aspectFill" @click="previewImage(item.dst_imgs, i)"></image>
								</view>
							</view>
							<view class="files">
								<view class="file-box" v-for="(file, i) in item.files_show" :key="i">
									<zy-file :src="file.path" :name="file.name" :size="file.size"></zy-file>
								</view>
							</view>
						</view>
					</view>
					<view class="key-result" v-if="item.keyResultsTaskList">
						<view class="kr-list" v-for="(res, index) in item.keyResultsTaskList" :key="index">
							<text-editor :id-name="`editorKeyList${res.id}`" :read-only="true" 
							:info="{content: res.content, height: 'auto'}"></text-editor>
							<view class="all-img-file" v-if="res.files.length>5">
								
								<view class="imgs">
									<view class="img-box" v-for="(path, i) in res.dst_imgs" :key="i" @click="previewImage(res.dst_imgs, i)">
										<image class="img" :src="path" mode="aspectFill"></image>
									</view>
								</view>
								<view class="files">
									<view class="file-box" v-for="(file, i) in res.files_show" :key="i">
										<zy-file :src="file.path" :name="file.name" :size="file.size"></zy-file>
									</view>
								</view>
							</view>
							
						</view>
					</view>
				</view>
				<view class="time-publish">
					<text>发布时间：{{handleTime(item.update_time)}}</text>
				</view>
				
				<view class="eva-content" v-if="item.state==2">
					<view class="tea-info">
						<image :src="item.teaPic?api.xiaodeObsUrl+item.teaPic:'/static/te1.png'" mode="aspectFill"></image>
						<text>{{item.teaName}}</text>
					</view>	
					<view class="eva-score">
						<image :src="`/static/score${i<=item.score_teacher?1:''}.png`" v-for="i in 3" :key="i" mode="aspectFill"></image>
					</view>
					<view class="eva-text">
						{{item.evaluate_content}}
					</view>
				</view>
			</view>
		</view>
		<uni-load-more :status="loadMore" color="#BFBFBF"></uni-load-more>
		<uni-transition mode-class="fade"
			:styles="utils.transitionStyles.bg" :show="showTask" @click="closePopup">
		</uni-transition>
		
		<uni-transition :mode-class="['slide-bottom']"
			:styles="select_class"
			:show="showTask">
			<view class="all-task">
				<view class="item" v-for="(item, i) in exampleTask" :key="i" @click="onclickTask(item)">
					{{item.content}}
				</view>
			</view>
		</uni-transition>
        <upload-file :show="showUpload"
		userType="2"
		:userId="userId"
		@clickEmoji="clickEmoji"
		@chooseFile="chooseFile"
		@close="closePopup"
		></upload-file>
	</view>
</template>
<script>
import uploadFile from "./upload-file.vue"
import textEditor from './text-editor.vue'
export default {
    components: {
        uploadFile,
		textEditor
    },
	data() {
		return {
			showTask: false, // 显示选择任务弹窗
			selectTaskInfo: {}, // 当前选择的任务信息
			// 上传文件和表情
			userId: -1, // 用户ID
			showUpload: false, // 是否显示上传文件的模块
			sendImages: [], // 需要提交的图片
			sendfiles: [], // 需要提交的文件
			editorInfo: {
				show: true,
				showUpload: false,
				content: '',
				placeText: '写下你的任务完成情况，【取得很大的进步...】使用形容词的描述很不具体，试着用【已完成xx任务，知道xx知识】因为描述具体、可量化，你的成长道路越清晰'
			},
			keyeditorInfo: {
				show: true,
				showUpload: false,
				content: '',
				height: '42rpx',
				placeText: '添加关键结果，将纳入到你的活动足迹中'
			},
			
			select_class: {
				position: 'fixed',
				/* #ifdef H5 */
				left: 'var(--window-left)',
				right: 'var(--window-right)',
				bottom: '44px',
				/* #endif */
				/* #ifndef H5 */
				left: 0,
				right: 0,
				bottom: '0',
				/* #endif */
				
				height: '312rpx',
				'z-index': 9
			},
			vocationLabourList: [], // 榜样劳动列表
			keyResults: [{}], // 关键值结果
			exampleTask: [], // 榜样任务列表
			exampleInfo: {}, // 榜样信息
			taskDeadline: '', // 任务过期时间
			taskStartTime: '', // 任务开始时间
			keyI: 0, // 添加关键结果下标
			currentPage: 1, // 当前页
			loadMore: 'more'
		}  
	},
	props: {
		onShow: { // 监听页面执行onShow
			type: Number,
			default: 0
		},
		onReachBottom: { // 监听页面上滑
			type: Number,
			default: 0
		},
		accountId: { // 账号ID 
			type: String,
			default: ''
		},
		studentId: { // 学生id
			type: String,
			default: ''
		}
    },
	watch: {
		onShow(val){
			this.initData()
		},
		onReachBottom(val){
			if(this.loadMore == 'more'){
				this.currentPage ++
				this.getExampleActivety()
			}
		}
	},
	mounted(){
		this.userId = uni.getStorageSync('tokenObj').userId

		this.initData()
		if(this.exampleTask.length==0){
			this.getExampleTask()
			this.getBindExample()
		}
	},
	methods: {
		handleTime(time){
			if(!time) return
			time = time.split(' ')[0].split('-').join('.')
			return time
		},
		initData(){
			this.currentPage = 1
			this.vocationLabourList = []
			this.getExampleActivety()
		},
		// 查询榜样劳动
		getExampleActivety(){
			this.loadMore = 'loading'
			this.api.get('example/findExampleActivetyPage', {
				accountId: this.accountId,
				page: this.currentPage,
				limit: 10
			}).then(res=>{
				if(res.data.state!='ok') return;
				this.loadMore = 'more'
				let pageData = res.data.exampleActivetyPage;
				this.vocationLabourList = pageData.list
				for(let i=0; i<pageData.list.length; i++){
					if(pageData.list[i].files.length>5){
						this.handleFilesShow(pageData.list[i].files, i, pageData.list[i])
					}
					if(pageData.list[i].keyResultsTaskList){
						let keyRes = pageData.list[i].keyResultsTaskList

						for(let j=0; j<keyRes.length; j++){
							let res = keyRes[j]
	
							if(res.files.length>5){
								this.handleFilesShow(res.files, i, res)
							}
							
						}
					}
					
				}
				if(pageData.totalPage <= this.currentPage){
					this.loadMore = 'no-more'
				}
			})
		},
		// 发表职业劳动
		commitExampleActivity(){
			if(!this.selectTaskInfo.id || !this.editorInfo.content) return;
			let list = [], files = [];
			files = this.sendImages.concat(this.sendfiles)
			for(let i=0; i<this.keyResults.length; i++){
				let item = this.keyResults[i],
				images = item.sendimgs || [],
				fs = item.sendfiles || [];
				if(item.content || images.length>0 || fs.length){
					list.push({content: item.content, files: images.concat(fs)})
				}
			}
			// return
			this.api.post('example/commitExampleActivity', {
				accountId: this.accountId,
				taskAlignmentId: this.selectTaskInfo.id,
				content: this.editorInfo.content,
				files: JSON.stringify(files),
				keyResults: JSON.stringify(list)
			}).then(res=>{
				if(res.data.state!='ok') return
				this.editorInfo.content = ''
				this.$refs.editorTask.closeHtml()
				this.selectTaskInfo = {};
				this.sendImages = []
				this.sendfiles = []
				this.keyResults = []
				this.utils.showToast('发布成功')
				setTimeout(()=>{
					this.initData()
				}, 1000)
			})
		},
		// 获取重要他人
		getBindExample(){
			this.api.get('sExample/findBindExample', {
				studentId: this.studentId
			}).then(res=>{
				if(res.data.state == 'ok'){
					let info = res.data.example || {};

					this.exampleInfo = info;
				}
			})
		},
		// 获取重要他人任务
		getExampleTask(){
			this.api.get('sExample/getExampleTask', {
				studentId: this.studentId
			}).then(res=>{
				let tasks = res.data.setList.reverse();
				this.exampleTask = tasks;
				let oneTaskInfo = tasks[0] || {}
				if(!oneTaskInfo.deadline) return
				this.taskDeadline = this.utils.dateFormat(oneTaskInfo.deadline.split(' ')[0])
				this.taskStartTime = this.utils.dateFormat(oneTaskInfo.updateTime.split(' ')[0])
			})
		},
        seeDetails(){
            uni.navigateTo({
                url: '/pages/student/example-details'
            })
        },
		chooseFileTask(type, list, sendList){
			if(type==1){
				this.sendImages = this.sendImages.concat(sendList)
				if(this.sendImages.length>9){
					this.utils.showToast('最多可以上传9张图片')
					this.sendImages.splice(9)
				}
			}else{
				this.sendfiles = this.sendfiles.concat(sendList)
				if(this.sendfiles.length>3){
					this.utils.showToast('最多可以上传3个文件')
					this.sendfiles.splice(3)
				}
			}
			
		},
		// 职业体验
		selectTask(){
			if(this.exampleTask.length==0){
				this.utils.showToast('还未设置重要他人任务')
				return
			}
			this.showTask = true
		},
		onclickTask(item){
			this.selectTaskInfo = item
			this.closePopup()
		},
		delResults(i){
			this.keyResults.splice(i, 1)
			this.keyResults.splice(i, 1)
		},
		addResults(){
			if(this.keyResults.length==5) return
			this.keyResults.push(1)
		},
        
		
		
		clickEmoji(str){
			let obj = this.keyResults[this.keyI] || {}
			let cont = obj.content || ''
			obj.content = cont+str;
			this.$set(this.keyResults, this.keyI, obj)
			
		},
		chooseFile(type, list, sendList){
			let info = this.keyResults[this.keyI] || {}
			
			let sendimgs = info.sendimgs || [],
				sendfiles = info.sendfiles || []
			if(type==1){
				sendimgs = sendimgs.concat(sendList)
				if(sendimgs.length>9){
					this.utils.showToast('最多可以上传9张图片')
					sendimgs.splice(9)
				}
			}else{
				sendfiles = sendfiles.concat(sendList)
				if(sendfiles.length>3){
					this.utils.showToast('最多可以上传3个文件')
					sendfiles.splice(3)
				}
			}
			info.sendimgs = sendimgs
			info.sendfiles = sendfiles
			this.$set(this.keyResults, this.keyI, info)
		},
        
		bindfocus1(e, i){
			this.keyI = i
			this.currentInput = 3;
			this.showUpload = true
			this.$refs.editorTask.close()
		},
		bindblur1(e, i){
			
		},
		bindinput1(e, i){
			let obj = this.keyResults[i] || {}
			obj.content = e.detail.value
			this.$set(this.keyResults, i, obj)
		},
		onEditorReady1(e){
				uni.createSelectorQuery().select('#editorkey').context((res) => {
				this.editorCtx1 = res.context
			}).exec()
		},
		closePopup(){
			this.showUpload = this.showTask = false
		},
		delFiles(i, sendItem){
			sendItem.splice(i, 1)
		},
		delkeyFiles(i, type, index, file){
			if(type==1){
				this.keyResults[index].sendimgs.splice(i, 1)
			}else{
				this.keyResults[index].sendfiles.splice(i, 1)
			}

			// this.$set(file, index, item)
			this.$set(this.keyResults, index, file)
		},
		// 区分显示图片和文件
		handleFilesShow(list, index, item){
			list = JSON.parse(list)
			let imgs = [], files = [], dst_files = []
			for(let i=0; i<list.length; i++){
				if(list[i].msgType==8){
					files.push(list[i].path)
					dst_files.push(list[i])
				}else{
					imgs.push(`${this.api.xiaodeObsUrl}${list[i].path}`)
				}
				
			}
			if(item){
				item.files_show = dst_files
				item.dst_imgs = imgs
				let obj = this.vocationLabourList[index]
				this.$set(this.vocationLabourList, index, obj)
			}else{
				let obj = this.vocationLabourList[index]
				obj.files_show = dst_files
				obj.dst_imgs = imgs
				this.$set(this.vocationLabourList, index, obj)
			}

		},
		previewImage(list, i){
			uni.previewImage({
				current: i,
				urls: list,
				longPressActions: {
					itemList: [],
					success: function(data) {
						
					},
					fail: function(err) {
						console.log(err.errMsg);
					}
				}
			});
		},
	}
}
</script>
<style lang="less" scoped>
	.example-task{
		padding: 0 32rpx;
	}
	.example-info{
		display: flex;
		align-items: center;
		padding: 26rpx 0;
		.head{
			width: 100rpx;
			height: 100rpx;
			border-radius: 50rpx;
			background-color: rgb(40, 194, 205, .5);
			image{
				margin: 6rpx;
				width: 88rpx;
				height: 88rpx;
				border-radius: 50%;
			}
		}
		.see-details{
			color: #999999;
		}
		.name-time{
			width: 100%;
			margin-left: 18rpx;
		}
		.name-see{
			display: flex;
			justify-content: space-between;
			align-items: center;
		}
		.name{
			font-weight: 600;
		}
		.time{
			margin-top: 12rpx;
			font-size: 24rpx;
			color: #999999;
		}
	}
	.task-content{
		background-color: #fff;
		padding: 32rpx;
	}
    .task-title{
        color: #333333;
        display: flex;
        justify-content: space-between;
        align-items: center;
        
    }
	.state{
		position: relative;
		padding-left: 20rpx;
		color: #28C2CD;
		font-size: 24rpx;
	    line-height: 32rpx;
		&::after{
			position: absolute;
			content: '';
			width: 10rpx;
			height: 10rpx;
			border-radius: 50%;
			top: 12rpx;
			left: 0%;
			// transform: translateY(-5rpx);
			background-color: #28C2CD;
		}
	}
	.state1{
		color: #FF4F01;
		&::after{
			background-color: #FF4F01;
		}
	}
	.state2{
		color: #999999;
		&::after{
			background-color: #999;
		}
	}
    .textarea-box{
		
		background-color: #F4F4F4;
		border-radius: 20rpx;
		padding: 32rpx;
		.tips{
			margin-top: 32rpx;
			font-size: 24rpx;
			color: #999;
		}
		textarea{
			width: 100%;
			height: 32rpx;
			font-size: 28rpx;
			margin-bottom: 24rpx;
		}
	}
	.time-publish{
		margin-top: 24rpx;
		color: #999;
		font-size: 24rpx;
	}
	.pub-btn{
		margin-top: 32rpx;
		height: 80rpx;
		line-height: 80rpx;
		color: #fff;
		border-radius: 20rpx;
		background-color: #28C2CD;
		font-size: 32rpx;
		text-align: center;
	}
	.textarea-box1{
		margin-top: 32rpx;
		border-radius: 20rpx;
		border: 1rpx solid #EEEEEE;
		padding: 32rpx;
		.content{
			p{
				display: flex;
				align-items: center;
				flex-wrap: wrap;
			}
		}
	}
	.all-img-file{
		margin-top: 32rpx;
		font-size: 0;
		.img{
			width: 194rpx;
			height: 194rpx;
			border-radius: 8rpx;
		}
		.close{
			position: absolute;
			top: 0;
			right: 0;
			width: 40rpx;
			height: 40rpx;
		}
		
	}
	.img-box{
		display: inline-block;
		width: 194rpx;
		height: 194rpx;
		position: relative;
		margin-right: 18rpx;
		margin-bottom: 20rpx;
		&:nth-child(3n){
			margin-right: 0;
		}
	}
	.file-box{
		margin-top: 32rpx;
		width: 560rpx;
		position: relative;
	}
	.eva-content{
		margin-top: 64rpx;
		position: relative;
		&::after{
			position: absolute;
			left: 0;
			top: -32rpx;
			content: '';
			width: 200%;
			border-width: 2rpx;
			border-style: dashed;
			border-color: #000;
			transform: scale(0.5) translateX(-50%);
            opacity: .1;
		}
	}
	.tea-info{
		display: flex;
		align-items: center;
		color: #333333;
		image{
			width: 78rpx;
			height: 78rpx;
			border-radius: 156rpx;
			margin-right: 24rpx;
		}
	}
	.eva-score{
		margin: 24rpx 0;
		image{
			margin-right: 17rpx;
			width: 34rpx;
			height: 32rpx;
		}
	}
	.eva-text{
		color: #666666;
		font-size: 28rpx;
		line-height: 44rpx;
	}
   
	.pro-exp-box{
		background: #fff;
		padding: 40rpx 0;
	}
	.pro-exp-title{
        color: #333333;
		margin-bottom: 32rpx;
		font-weight: 600;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	.task-line, .kr-list{
		position: relative;
		padding-bottom: 40rpx;
		box-sizing: content-box;
		&::after{
			position: absolute;
			left: 0;
			bottom: 0;
			content: '';
			width: 200%;
			border-width: 2rpx;
			border-style: dashed;
			border-color: #EEEEEE;
			transform: scale(0.5) translateX(-50%);
		}
	}
	.key-result{
		
		
	}
	.kr-list{
		padding: 40rpx 0;
		&::after{
			border: none;
		}
	}
	.k-text{
		display: flex;
		justify-content: space-between;
		align-items: center;
		textarea{
			width: 90%;
			height: 42rpx;
			font-size: 28rpx;
			margin-bottom: 0;
		}
	}
	.add-btn{
		margin-top: 39rpx;
	}
	
	// 选择任务的弹窗
	.all-task{
		// position: absolute;
		// width: 100%;
		background: #FFFFFF;
		padding: 0 32rpx;
		text-align: center;
		.item{
			padding: 32rpx 32rpx;
			font-size: 28rpx;
			border-bottom: 2rpx solid #eee;
		}
	}
</style>